package com.base.cn.platform.os.common.interceptor;

import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.common.utils.web.WebMobileLoginUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.entity.planTools.OverallAdvert;
import com.base.cn.platform.os.entity.user.integral.IntegralRule;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.config.SysLinkConfigService;
import com.base.cn.platform.os.service.manage.help.SysHelpCenterService;
import com.base.cn.platform.os.service.manage.marketing.baseShare.MarketingBaseShareService;
import com.base.cn.platform.os.service.manage.netSchoolConfig.publicAccount.PublicAccountService;
import com.base.cn.platform.os.service.manage.planTools.OverallAdvertService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralRuleService;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 基础数据拦截器
 *
 * @author s.li
 * @create 2018-03-07 10:25
 */
public class BaseDataInterceptor implements HandlerInterceptor {
    @Autowired
    private CommonConstants commonConstants;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SysHelpCenterService sysHelpCenterService;
    @Autowired
    private SysLinkConfigService sysLinkConfigService;
    @Autowired
    private WebMobileLoginUtil webMobileLoginUtil;
    @Autowired
    private MarketingBaseShareService marketingBaseShareService;
    @Autowired
    private PublicAccountService publicAccountService;
    @Autowired
    private CusUserIntegralRuleService cusUserIntegralRuleService;
    @Autowired
    private OverallAdvertService overallAdvertService;
    //代码版本
    private static long version = System.currentTimeMillis();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String url = request.getRequestURI();
        if(!url.startsWith("/noAuthority") && !url.startsWith("/admin") && !url.startsWith("/web") && !url.startsWith("/mobile") && !url.startsWith("/login") && !url.startsWith("/notLoginJump") && !url.startsWith("/register")){
            return true;
        }
        String accept = request.getHeader("Accept");
        //如果是ajax请求则不需要设置
        if(WebUtils.isAjaxRequest(request) && accept!=null && accept.contains("json")){
            return true;
        }

        String staticPath = commonConstants.get(CommonConstants.STATIC_PATH);
        request.setAttribute("staticPath",staticPath);
        String uploadPath = commonConstants.get(CommonConstants.UPLOAD_PATH);
        request.setAttribute("uploadPath",uploadPath);
        String mobilePath = commonConstants.get(CommonConstants.MOBILE_PATH);
        request.setAttribute("mobilePath",mobilePath);
        String webPath = commonConstants.get(CommonConstants.WEB_PATH);
        request.setAttribute("webPath",webPath);

        TreeMap<String,String> versionMap = sysConfigService.getSysConfigContext(ConfigName.VERSION);
        long _version = Long.parseLong(versionMap.get("version"));
        if(version > _version){
            request.setAttribute("v",version);
        }else{
            request.setAttribute("v",_version);
        }
        String ctx =WebUtils.getContextPath(request);
        request.setAttribute("ctx",ctx);

        TreeMap<String,String> saleMap = sysConfigService.getSysConfigContext(ConfigName.SALE);
        String selaSwitch = saleMap.get("selaSwitch");
        request.setAttribute("selaSwitch",selaSwitch);
        //平台信息数据
        TreeMap<String,String> infoMap = sysConfigService.getSysConfigContext(ConfigName.INFO);
        request.setAttribute("infoMap",infoMap);
        //ICO图片信息数据
        TreeMap<String,String> icoMap = sysConfigService.getSysConfigContext(ConfigName.ICO);
        request.setAttribute("icoMap",icoMap);
        //logo数据
        TreeMap<String,String> logoMap = sysConfigService.getSysConfigContext(ConfigName.LOGO);
        request.setAttribute("logoMap",logoMap);
        //客服链接
        TreeMap<String,String> serviceMap = sysConfigService.getSysConfigContext(ConfigName.SERVICE);
        request.setAttribute("serviceMap",serviceMap);

        JsonObject user = webMobileLoginUtil.getLoginUser(request);
        if(url.startsWith("/web")||url.startsWith("/mobile")) {//前台路径拦截
            IntegralRule userIntegralRuleName= cusUserIntegralRuleService.getUserIntegralRuleByKey(ActionKey.NAME);
            TreeMap<String, String> contextTreeMap4 = userIntegralRuleName.getContextTreeMap();
            request.setAttribute("userIntegralRuleName",contextTreeMap4);
        }
        if(url.startsWith("/web")){//前台路径拦截
            //第三方网站统计代码
            TreeMap<String,String> countCodeMap = sysConfigService.getSysConfigContext(ConfigName.COUNTCODE);
            request.setAttribute("countCodeMap",countCodeMap);
            //前台判断二维码开关
            TreeMap<String, String> onOffSwitch = sysConfigService.getSysConfigContext(ConfigName.ONOFF);
            request.setAttribute("onOffSwitch",onOffSwitch);
            //H5站二维码
            TreeMap<String,String> h5MobileMap = sysConfigService.getSysConfigContext(ConfigName.H5AMOBILE);
            request.setAttribute("h5MobileMap",h5MobileMap);
            //小程序二维码
            TreeMap<String,String> smallAppMap = sysConfigService.getSysConfigContext(ConfigName.SMALLAPP);
            request.setAttribute("smallAppMap",smallAppMap);
            //App下载二维码
            TreeMap<String,String> appDowMap = sysConfigService.getSysConfigContext(ConfigName.APPDOW);
            request.setAttribute("appDowMap",appDowMap);
            //底部帮助文档
            List<Map<String,Object>> helpList = sysHelpCenterService.findWebFooterHelp();
            request.setAttribute("helpList",helpList);
            OverallAdvert overallAdvert = overallAdvertService.overallAdvertInfo();
            request.setAttribute("overallAdvert",overallAdvert);
            //导航、底部链接、友情链接
            Map<String,List<Map<String,Object>>> linkMapList = sysLinkConfigService.findWebLinkMapList();
            if(linkMapList!=null){
                List<Map<String,Object>> friendship_link_list = linkMapList.get("friendship_link");//友情链接
                List<Map<String,Object>> navigation_list = linkMapList.get("navigation");//导航链接
                List<Map<String,Object>> bottom_tag_list = linkMapList.get("bottom_tag");//底部链接
                request.setAttribute("friendship_link",friendship_link_list);
                request.setAttribute("navigation",navigation_list);
                request.setAttribute("bottom_tag",bottom_tag_list);
            }
            //获取前台登录用户信息(非ajax请求再设置)
            user = webMobileLoginUtil.getLoginUser(request);
        }
        if(url.startsWith("/mobile")){
            TreeMap<String,String> appDowMap = sysConfigService.getSysConfigContext(ConfigName.APPDOW);
            request.setAttribute("appDowMap",appDowMap);
            //后台海报分享设置
            Map<String,Object> params = new HashMap<>();
            Map<String, Object> objectMap = marketingBaseShareService.queryBaseShare(params);
            String shareChannel = objectMap.get("shareChannel").toString();
            request.setAttribute("shareChannel",shareChannel);
            //查询分享链接公众号信息
            HashMap<String, Object> account = new HashMap<>();
            account.put("configType","SHARE");
            List<Map<String, Object>> accountList = publicAccountService.queryPublicAccount(account);
            Map<String, Object> map = accountList.get(0);
            request.setAttribute("accountList",map);

        }
        if(ObjectUtils.isNotEmpty(user)){
            Gson gson = new Gson();
            Map map = new HashMap<>();
            map = gson.fromJson(user.toString(), map.getClass());
            request.setAttribute("SHARE_KEY",  webMobileLoginUtil.getShareKey(request));
            request.setAttribute("userMap",map);
        }
        return true;
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
